package atmosphere;

import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AppStateManager;
import com.jme3.audio.AudioNode;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.post.HDRRenderer;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Spatial;
import com.jme3.scene.Spatial.CullHint;
import com.jme3.scene.shape.Sphere;
import com.jme3.texture.Image;
import com.jme3.texture.TextureCubeMap;

/**
 * This is a small prototype that integrates the atmosphere scattering shaders
 * developed by Sean O'Neil in a JME3 example.
 *
 * Notes:
 *
 * The planet consists of two icospheres (the mesh has been exported from blender),
 * one for the ground and one for the outer atmosphere.
 * Each icosphere uses two materials (see in MatDefs folder). One when the
 * camera is in outer space and the other when it is inside the atmosphere.
 *
 * On the upper left corner there are a few parameters that can be changed using
 * the keys in brackets. Press shift+key to decrease a value.
 *
 * 
 * @author jiyarza
 */
public class Prototype extends SimpleApplication {

    // Singleton
    private static Prototype instance;

    private DirectionalLight sun;
    private Planet planet;
    public final static Vector3f PLANET_POSITION = new Vector3f(0.0f, 0.0f, 0.0f);
    public final static float PLANET_RADIUS = 200f; // Km
    public final static Vector3f lightPosition = new Vector3f(0, 0f, - PLANET_RADIUS * 10f);
    public final static Vector3f LIGHT_DIRECTION = PLANET_POSITION.subtract(lightPosition).normalize();

    // starting angle for the sun light
    float angle = 3.14159f;

    // experimental, not being used by default
    private HDRRenderer hdrRender;
    
    public static void main(String[] args) {
        Prototype app = Prototype.getInstance();
        app.start();
    }

    private Prototype() {
    }

    public static Prototype getInstance() {
        if (instance == null) {
            instance = new Prototype();
        }
        return instance;
    }

    @Override
    public void simpleInitApp() {
        rootNode.setCullHint(CullHint.Never);
        setupCamera();
        setupSkyBox("blue-glow-1024");
        // Uncomment to try HDR (better planet illumination, when you find the right angle))
        //HDRInit();
        setupLights();

        planet = new Planet(PLANET_RADIUS, PLANET_POSITION);
        stateManager.attach(new PlanetRendererState(planet, sun));
        stateManager.attach(new PlanetUIState(planet));
        stateManager.attach(new JukeboxState());
    }
    
    private void HDRInit() {
        hdrRender = new HDRRenderer(assetManager, renderer);
        hdrRender.setSamples(0);
        hdrRender.setMaxIterations(0);
        hdrRender.setExposure(0.0005f);
        hdrRender.setThrottle(0.5f);

        viewPort.addProcessor(hdrRender);
    }

    @Override
    public void simpleUpdate(float tpf) {
        // Rotate the sun light
        angle += tpf * 0.01;
        sun.setDirection(new Vector3f(-FastMath.sin(angle) * PLANET_RADIUS, FastMath.HALF_PI,
                                       FastMath.cos(angle) * PLANET_RADIUS).normalize());
    }

    /**
     * Create scene lights
     */
    public void setupLights() {
        sun = new DirectionalLight();
        sun.setDirection(LIGHT_DIRECTION);
        sun.setColor(ColorRGBA.White);
        rootNode.addLight(sun);
    }

    /**
     * Create the sky box
     */
    public void setupSkyBox(String name) {
        Mesh sphere = new Sphere(32, 32, 10f);
        sphere.setStatic();
        Spatial geometry = new Geometry("SkyBox", sphere);
        geometry.setQueueBucket(Bucket.Sky);
        geometry.setShadowMode(ShadowMode.Off);

        Image cube = assetManager.loadTexture("Textures/blue-glow-1024.dds").getImage();
        TextureCubeMap cubemap = new TextureCubeMap(cube);

        Material mat = new Material(assetManager, "Common/MatDefs/Misc/Sky.j3md");
        mat.setBoolean("SphereMap", false);
        mat.setTexture("Texture", cubemap);
        mat.setVector3("NormalScale", new Vector3f(1, 1, 1));
        geometry.setMaterial(mat);
        
        rootNode.attachChild(geometry);
    }

    /**
     * Configure the camera relative to planet position and size
     */
    public void setupCamera() {
        cam.setFrustumFar(PLANET_RADIUS * 100f);
        flyCam.setMoveSpeed(PLANET_RADIUS * 0.05f);
        farView();
    }

    public void closeView() {
        cam.setLocation(new Vector3f(PLANET_POSITION.x + PLANET_RADIUS,
                    PLANET_POSITION.y, PLANET_POSITION.z + PLANET_RADIUS));
        cam.lookAt(lightPosition, cam.getUp());
    }

    public void farView() {
        cam.setLocation(new Vector3f(PLANET_POSITION.x + PLANET_RADIUS * 2f,
                    PLANET_POSITION.y, PLANET_POSITION.z + PLANET_RADIUS * 2f));
        cam.lookAt(PLANET_POSITION, cam.getUp());
    }

    public void atmosphericSpeed() {
        flyCam.setMoveSpeed(PLANET_RADIUS * 0.01f);
    }

    public void outerSpaceSpeed() {
        flyCam.setMoveSpeed(PLANET_RADIUS * 0.05f);
    }
}
